﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ActionModel.WebModel;
using System.IO;
using System.Text;
using ActionModel.Utility;

namespace FilesArranger
{
	/// <summary>
	/// FileTreeActions 的摘要说明
	/// </summary>
	public class FileTreeActions : MultiActionAjaxHandler
	{
		protected override void RegisterAction()
		{
			this.ActionDict.Add("LoadChildren", new Action(LoadChildren));
			this.ActionDict.Add("DeleteChildNode", new Action(DeleteChildNode));
			this.ActionDict.Add("CreateFolderNode", new Action(CreateFolderNode));
			this.ActionDict.Add("CreateFileNode", new Action(CreateFileNode));
			this.ActionDict.Add("MoveFolderNode", new Action(MoveFolderNode));
			this.ActionDict.Add("MoveFileNode", new Action(MoveFileNode));
			this.ActionDict.Add("Refresh", new Action(Refresh));

			this.ActionDict.Add("DeleteFolder", new Action(DeleteFolder));
			this.ActionDict.Add("DeleteFile", new Action(DeleteFile));
			this.ActionDict.Add("CreateFile", new Action(CreateFile));
			this.ActionDict.Add("EditFile", new Action(EditFile));
		}

		protected override void DoProcessRequest(HttpContext context)
		{
			
		}

		ITreeToDo treeToDo;

		void LoadChildren()
		{
			initTreeToDo();

			string valuePath = Request["ValuePath"];

			DivNode[] nodes = treeToDo.LoadChildren(valuePath);

			JsonResult.WriteSuccess(nodes);
		}

		protected void DeleteChildNode()
		{
			throw new NotImplementedException();
		}

		void CreateFolderNode()
		{
			initTreeToDo();

			string sourcePath = Request["sourcePath"];
			string jsonNode = Request["node"];
			DivNode node = JsonSerializer.FromJSON<DivNode>(jsonNode);

			treeToDo.CreateFolderNode(sourcePath, node, delegate(bool result, string message)
			{
				if (result)
				{
					JsonResult.WriteSuccess();
				}
				else
				{
					JsonResult.WriteError(message);
				}
			});
		}

		void CreateFileNode()
		{
			initTreeToDo();

			string sourcePath = Request["sourcePath"];
			string jsonNode = Request["node"];
			DivNode node = JsonSerializer.FromJSON<DivNode>(jsonNode);

			treeToDo.CreateFileNode(sourcePath, node, delegate(bool result, string message)
			{
				if (result)
				{
					JsonResult.WriteSuccess();
				}
				else
				{
					JsonResult.WriteError(message);
				}
			});
		}

		void MoveFolderNode()
		{
			initTreeToDo();

			string sourcePath = Request["sourceName"];
			string destinationPath = Request["destinationPath"];
			treeToDo.MoveFolderNode(sourcePath, destinationPath, delegate(bool result, string message)
			{
				if (result)
				{
					JsonResult.WriteSuccess();
				}
				else
				{
					JsonResult.WriteError(message);
				}

			});
		}

		void MoveFileNode()
		{
			initTreeToDo();

			string sourcePath = Request["sourceName"];
			string destinationPath = Request["destinationPath"];
			treeToDo.MoveFileNode(sourcePath, destinationPath, delegate(bool result, string message)
			{
				if (result)
				{
					JsonResult.WriteSuccess();
				}
				else
				{
					JsonResult.WriteError(message);
				}

			});
		}

		protected void Refresh()
		{
			string jsonPathTree = Request["PathTree"];
			jsonPathTree = jsonPathTree.Replace("\"\":", "\"\\/\":");
			IDictionary<string, object> pathsExpandRecord = JsonSerializer.FromJSON<IDictionary<string, object>>(jsonPathTree);

			DivNode[] nodes = treeToDo.Refresh(pathsExpandRecord);
			JsonResult.WriteSuccess(nodes);
		}

		void initTreeToDo()
		{
			if (Request.QueryString["rootid"] == "SiteBrowseTree")
				treeToDo = new SiteBrowseTreeToDo();
			else if (Request.QueryString["rootid"] == "FakeTree")
				treeToDo = new FakeTreeToDo();
			else
				JsonResult.WriteError("tree root id unkown");
		}

		void DeleteFolder()
		{
			
		}
		void DeleteFile()
		{
			
		}
		void CreateFile()
		{
			try
			{
				string PathName = Request.MapPath(Request["PathName"]);
				File.Create(PathName).Close();
			}
			catch (Exception ex)
			{
				Response.StatusCode = 500;
				Response.Write(ex.Message);
				Response.End();
			}
		}
		void EditFile()
		{
			try
			{
				string PathName = Request.MapPath(Request["PathName"]);
				string CodePage = Request["CodePage"];
				Encoding enc = null;
				short code = 936;
				bool isNum = short.TryParse(CodePage, out code);
				if (isNum)
				{
					try
					{
						enc = Encoding.GetEncoding(code);
					}
					catch
					{
						enc = Encoding.GetEncoding(936);
					}
				}
				else
				{
					try
					{
						enc = Encoding.GetEncoding(CodePage);
					}
					catch
					{
						enc = Encoding.GetEncoding("GB18030");
					}
				}
				EditFile(PathName, enc);
			}
			catch (Exception ex)
			{
				Response.StatusCode = 500;
				Response.Write(ex.Message);
				Response.End();
			}
		}

		/// <summary>
		/// 编辑文件
		/// </summary>
		/// <param name="path">文件路径</param>
		/// <param name="encoding">读取文件的编码</param>
		void EditFile(string path, Encoding encoding)
		{
			Response.ContentType = "text/plain";
			//StreamReader sr = new StreamReader(path, Encoding.Default);
			//string content = sr.ReadToEnd();
			string content = File.ReadAllText(path, encoding);
			//sr.Close();
			//byte[] content_bytes_UTF8 = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding(936), encoding.GetBytes(content));
			//string Content_UTF8 = Encoding.UTF8.GetString(content_bytes_UTF8);
			Response.Write(content);
		}

		public override bool IsReusable
		{
			get { throw new NotImplementedException(); }
		}
	}
}